import { ITypeLogin } from './type'
import { IRoterType } from '../type'
import { Module } from 'vuex'
import {
  getUserInfoRequest,
  loginRequest,
  getUserMenuRequest
} from '@/service/login/login'
import { userInfoType } from '@/service/login/type'
import cache from '@/utils/cache'
import router from '@/router'
import { addRouteList } from '@/utils/map-menu'
const user: Module<ITypeLogin, IRoterType> = {
  namespaced: true,
  state: {
    userInfo: {},
    token: '',
    menu: []
  },
  getters: {},
  mutations: {
    saveToken(state, token: string) {
      state.token = token
    },
    saveUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    saveUserMenu(state, userMenu: any) {
      state.menu = userMenu
      //动态添加路由
      addRouteList(userMenu).forEach((item) => {
        router.addRoute('Main', item)
      })
    }
  },
  actions: {
    async InitiateLogin({ commit, dispatch }, userInfo: userInfoType) {
      const res = await loginRequest(userInfo)
      console.log(res)
      const { id, token } = res.data
      //保存token
      commit('saveToken', token)
      cache.setCache('cms-token', token)

      //请求保存用户信息
      const userRes = await getUserInfoRequest(id)
      commit('saveUserInfo', userRes.data)
      cache.setCache('cms-userInfo', userRes.data)
      //请求保存用户权限菜单
      const userMenu = await getUserMenuRequest(id)
      commit('saveUserMenu', userMenu.data)
      cache.setCache('cms-userMenu', userMenu.data)
      //请求菜单数据  因为要确保有token和userInfo
      dispatch('getRoleAndDepartData', null, { root: true })
      //跳转主页
      router.push('Main')
    },
    loadState({ commit }) {
      const token = cache.getCache('cms-token')
      if (token) {
        commit('saveToken', token)
      }
      const userInfo = cache.getCache('cms-userInfo')
      if (userInfo) {
        commit('saveUserInfo', userInfo)
      }
      const userMenu = cache.getCache('cms-userMenu')
      if (userMenu) {
        commit('saveUserMenu', userMenu)
      }
    }
  }
}
export default user
